import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
const foodsStore = createSlice({
  name: "foods",
  initialState: {
    foodsList: [],
    asideActiveIndex: 0,
    cartList: [],
    visibleFlag: false
  },
  reducers: {
    addFoods: (state, action) => {
      state.foodsList = action.payload;
    },
    changeActiveIndex: (state, action) => {
      state.asideActiveIndex = action.payload;
    },
    addCartList: (state, action) => {
      let data = state.cartList.find(item => item.id === action.payload.id)
      if (data) {
        data.count = action.payload.count + 1
      } else {
        state.cartList.push(action.payload)
      }  
    },
    subCartList: (state, action) => { 
      
      if (action.payload.type === "subALL") {
        state.cartList = [] 
        state.visibleFlag = false
        return 
      }
      let index = state.cartList.findIndex(item => item.id === action.payload.id)
      console.log(index,action.payload);
      
       if (action.payload.count === 0) { 
        state.cartList.splice(index, 1)  
        if ( state.cartList.length === 0) {
          state.visibleFlag = false
        }
       }else{
        state.cartList[index].count = action.payload.count
       }
      
    },
    setVisibleFlag: (state, action) => {
      state.visibleFlag = action.payload
    }
  }
})
const { addFoods, changeActiveIndex ,addCartList,subCartList , setVisibleFlag} = foodsStore.actions;
const getFoodsData = () => {
  return async (dispatch) => {
    console.log("getFoodsData");
    const res = await axios.get("http://localhost:3004/takeaway");
    dispatch(addFoods(res.data));
  }
}
const foodsListReducer = foodsStore.reducer;
export { getFoodsData, addFoods, changeActiveIndex ,addCartList , subCartList ,setVisibleFlag};

export default foodsListReducer;